<template>
  <div class="task-list-container">
    <div class="task-list-header">
      <h2>任务列表</h2>
      <el-button type="primary" @click="handleCreateTask" v-if="isCompany">
        发布任务
      </el-button>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <el-input
        v-model="searchQuery"
        placeholder="搜索任务标题"
        class="search-input"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select v-model="jobTypeFilter" placeholder="任务类型" clearable @change="handleSearch">
        <el-option
          v-for="type in jobTypes"
          :key="type.value"
          :label="type.label"
          :value="type.value"
        />
      </el-select>

      <el-select v-model="statusFilter" placeholder="任务状态" clearable @change="handleSearch">
        <el-option
          v-for="status in statusOptions"
          :key="status.value"
          :label="status.label"
          :value="status.value"
        />
      </el-select>
    </div>

    <!-- 任务卡片列表 -->
    <div class="task-cards" v-loading="loading">
      <el-empty v-if="filteredTasks.length === 0" description="暂无任务" />
      
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="task in paginatedTasks" :key="task.id">
          <el-card class="task-card" shadow="hover" @click="handleTaskClick(task)">
            <template #header>
              <div class="task-card-header">
                <span class="task-title">{{ task.title }}</span>
                <el-tag :type="getStatusType(task.status)" size="small">
                  {{ getStatusText(task.status) }}
                </el-tag>
              </div>
            </template>
            
            <div class="task-card-content">
              <div class="task-info-item">
                <el-icon><Briefcase /></el-icon>
                <span>{{ task.jobType || '未指定' }}</span>
              </div>
              
              <div class="task-info-item">
                <el-icon><Location /></el-icon>
                <span>{{ task.location }}</span>
              </div>
              
              <div class="task-info-item">
                <el-icon><Money /></el-icon>
                <span>¥{{ task.salary }}</span>
              </div>
              
              <div class="task-info-item">
                <el-icon><Calendar /></el-icon>
                <span>{{ formatDate(task.createTime) }}</span>
              </div>
              
              <div class="task-description">
                {{ task.content?.substring(0, 50) }}{{ task.content?.length > 50 ? '...' : '' }}
              </div>
            </div>
            
            <div class="task-card-footer">
              <el-button type="primary" size="small" @click.stop="handleTaskClick(task)">
                查看详情
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[8, 16, 24, 32]"
        :total="filteredTasks.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, Briefcase, Location, Money, Calendar } from '@element-plus/icons-vue'
import { getTaskList } from '@/api/task'
import { formatDate } from '@/utils/format'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const tasks = ref([])
const searchQuery = ref('')
const jobTypeFilter = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(8)

// 判断是否为公司用户
const isCompany = computed(() => {
  return userStore.userInfo && userStore.userInfo.role === 'company'
})

// 任务类型选项
const jobTypes = [
  { value: 'development', label: '开发' },
  { value: 'design', label: '设计' },
  { value: 'marketing', label: '营销' },
  { value: 'writing', label: '写作' },
  { value: 'translation', label: '翻译' },
  { value: 'other', label: '其他' }
]

// 任务状态选项
const statusOptions = [
  { value: 'published', label: '已发布' },
  { value: 'assigned', label: '进行中' },
  { value: 'pending_completion', label: '待确认' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' }
]

// 过滤后的任务列表
const filteredTasks = computed(() => {
  return tasks.value.filter(task => {
    // 标题或内容匹配搜索词
    const matchQuery = !searchQuery.value || 
      (task.title && task.title.toLowerCase().includes(searchQuery.value.toLowerCase())) ||
      (task.content && task.content.toLowerCase().includes(searchQuery.value.toLowerCase()))
    
    // 任务类型匹配
    const matchJobType = !jobTypeFilter.value || task.jobType === jobTypeFilter.value
    
    // 任务状态匹配 - 保留状态筛选功能
    const matchStatus = !statusFilter.value || task.status === statusFilter.value
    
    // 返回匹配的任务
    return matchQuery && matchJobType && matchStatus
  })
})

// 分页后的任务列表
const paginatedTasks = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTasks.value.slice(start, end)
})

// 加载任务列表
const loadTasks = async () => {
  loading.value = true
  try {
    const response = await getTaskList()
    console.log('任务列表响应:', response)
    
    if (response && (response.data || Array.isArray(response))) {
      tasks.value = Array.isArray(response) ? response : (response.data || [])
      console.log(`成功加载 ${tasks.value.length} 个任务`)
    } else {
      console.error('获取任务列表响应格式错误:', response)
      ElMessage.error('获取任务列表失败')
    }
  } catch (error) {
    console.error('加载任务列表失败:', error)
    ElMessage.error('加载任务列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 获取状态样式
const getStatusType = (status) => {
  switch (status) {
    case 'published': return 'primary'
    case 'assigned': return 'success'
    case 'pending_completion': return 'warning'
    case 'completed': return 'info'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

// 获取状态文字
const getStatusText = (status) => {
  switch (status) {
    case 'published': return '已发布'
    case 'assigned': return '进行中'
    case 'pending_completion': return '待确认'
    case 'completed': return '已完成'
    case 'cancelled': return '已取消'
    default: return '未知状态'
  }
}

// 查看任务详情
const handleTaskClick = (task) => {
  router.push(`/task/${task.id}`)
}

// 发布任务
const handleCreateTask = () => {
  router.push('/task/create')
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 组件挂载时加载数据
onMounted(() => {
  loadTasks()
})
</script>

<style scoped>
.task-list-container {
  padding: 20px;
}

.task-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.task-cards {
  margin-bottom: 20px;
}

.task-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.task-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.task-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-title {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}

.task-card-content {
  padding: 10px 0;
}

.task-info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  color: #606266;
}

.task-info-item .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.task-description {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.task-card-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #EBEEF5;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media screen and (max-width: 768px) {
  .filter-section {
    flex-direction: column;
  }
  
  .search-input {
    width: 100%;
  }
}
</style> 